/**
 *
 */
package com.rf.richfitwheel.admin.sys.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rf.richfitwheel.admin.sys.dao.*;
import com.rf.richfitwheel.admin.sys.model.*;
import com.rf.richfitwheel.admin.sys.service.StationService;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.common.utils.StringUtils;
import com.rf.richfitwheel.common.utils.TreeUtils;
import com.rf.richfitwheel.common.utils.UuidUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * @author hushouquan
 *
 */
@Service("stationService")
public class StationServiceImpl implements StationService {

    @Autowired
    private StationMapper stationMapper;//注入dao
    @Autowired
    private SqlAdapterMapper sqlAdapterMapper;//注入dao
    @Autowired
    private StationMenuMapper stationMenuMapper;
    @Autowired
    private UserStationMapper userStationMapper;
    @Autowired
    private OrgMapper orgMapper;

    /**
     * 岗位管理
     * @author hushouquan
     * @throws Exception
     *
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) throws Exception {
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Station> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        JSONObject jsonObject = JSONObject.fromObject(params.get("dataForm"));
        if(jsonObject.get("orgId") == null){
            return pageUtils;
        }
        StationExample example = new StationExample();
        StationExample.Criteria criteria = example.createCriteria();
        criteria.andOrgIdEqualTo(jsonObject.getString("orgId"));
        if (StringUtils.isNotBlank(jsonObject.get("stationName"))) {
            criteria.andStationNameLike("%" + jsonObject.getString("stationName") + "%");
        }
        if (StringUtils.isNotBlank(jsonObject.get("moduleType"))) {
            criteria.andModuleTypeEqualTo(jsonObject.getString("moduleType"));
        }
        if(StringUtils.isNotBlank(params.get("moduleTypeHead"))){
            String moduleTypeHead = (String) params.get("moduleTypeHead");
            List<String> modList = new ArrayList<>(Arrays.asList(moduleTypeHead.split(",")));
            modList.add(Constant.SystemModule.sys.name());
            criteria.andModuleTypeIn(modList);
        }
        example.setOrderByClause(" mod_time desc  ");
        List<Station> list = stationMapper.selectByExample(example);
        pageUtils = new PageUtils(p);
        return pageUtils;
    }

    /**
     * 根据id查询岗位信息
     * @param id
     * @return
     */
    @Override
    public Station selectById(String id) {
        return stationMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增岗位
     * @param station
     * @param userVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addStation(Station station, UserVO userVO) {
        Date nowDate = new Date();
        station.setId(UuidUtil.get32UUID());
        station.setCreater(userVO.getId());
        station.setCreateTime(nowDate);
        station.setModTime(nowDate);
        station.setModUser(userVO.getId());
        station.setVersion(0);
        //String tenantId = orgMapper.selectByPrimaryKey(station.getOrgId()).getTenantId();
        //station.setTenantId(tenantId);
        stationMapper.insert(station);
    }

    /**
     * 修改岗位
     * @param station
     * @param user
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStation(Station station, UserVO user) {
        Date dateNow = new Date();
        Station record = stationMapper.selectByPrimaryKey(station.getId());
        record.setVersion(record.getVersion() + 1);
        record.setStationName(station.getStationName());
        record.setShortName(station.getShortName());
        record.setStatus(station.getStatus());
        record.setStationRank(station.getStationRank());
        record.setModUser(user.getId());
        record.setModTime(dateNow);
        record.setStationDesc(station.getStationDesc());
        record.setModuleType(station.getModuleType());
        stationMapper.updateByPrimaryKeySelective(record);
//		String tenantId = orgMapper.selectByPrimaryKey(station.getOrgId()).getTenantId();
//		//先删除角色资源关联再增加，非超级管理员只能删除自己租户的角色资源
//		if(user.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
////			sqlAdapterMapper.deleteSQL("delete from sys_station_menu where station_id='" + station.getId() + "'");
//			stationMenuMapper.deleteByStationId(station.getId());
//		}else {
//
////			sqlAdapterMapper.deleteSQL("delete from sys_station_menu where station_id='" + station.getId() + "' and menu_id in (select m.id from sys_menu m where m.tenant_id='" + tenantId + "')");
//			Map<String, Object> param = new HashMap<String, Object>();
//			param.put("stationId", station.getId());
//			param.put("tenantId", tenantId);
//			stationMenuMapper.deleteByStationIdAndTenantId(param);
//		}
    }


    /**
     * 删除岗位信息
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(String[] ids) {
        for (String id : ids) {
            //删除岗位资源关联
//			sqlAdapterMapper.deleteSQL("delete from sys_station_menu where station_id='" + id + "'");
            StationMenuExample example = new StationMenuExample();
            StationMenuExample.Criteria criteria = example.createCriteria();
            criteria.andStationIdEqualTo(id);
            stationMenuMapper.deleteByExample(example);
            //删除岗位用户关联
//			sqlAdapterMapper.deleteSQL("delete from sys_user_station where station_id='" + id + "'");
            UserStationExample example1 = new UserStationExample();
            UserStationExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andStationIdEqualTo(id);
            userStationMapper.deleteByExample(example1);
            stationMapper.deleteByPrimaryKey(id);
        }
    }

    /**
     * 批量清除岗位资源权限
     * @param ids
     * @param userVO
     */
    @Override
    public void deleteStationRes(String[] ids, UserVO userVO) {
        StationMenuExample example = new StationMenuExample();
        StationMenuExample.Criteria criteria = example.createCriteria();
        criteria.andStationIdIn(Arrays.asList(ids));
        stationMenuMapper.deleteByExample(example);
    }

    /**
     * 根据租户id获取岗位树
     * @param tenantId
     * @return
     * @throws Exception
     */
    @Override
    public List<TreeUtils> getAllStationTreeUtilsByTenantId(String tenantId) throws Exception {
        if (StringUtils.isBlank(tenantId)) {
            return new ArrayList<TreeUtils>();
        }
        Map<String, Object> paramsNew = new HashMap<String, Object>();
        paramsNew.put("status", Constant.COMMON_STATUS_NORMAL);
        paramsNew.put("tenantId", tenantId);
        List<Map<String, Object>> list = stationMapper.getAllStationTreeUtilsByTenantId(paramsNew);
        List<TreeUtils> listTree = TreeUtils.getTreeListMap(list, "id", "parentId", "stationName", "disabledfn", "iconfn");
        return listTree;
    }

    /**
     * 根据租户id获取岗位树，icon属性存的是id
     * @param tenantId
     * @return
     * @throws Exception
     */
    @Override
    public List<TreeUtils> getAllStationTreeUtilsIconFnIdByTenantId(String tenantId) throws Exception {
        if (StringUtils.isBlank(tenantId)) {
            return new ArrayList<TreeUtils>();
        }
        Map<String, Object> paramsNew = new HashMap<String, Object>();
        paramsNew.put("status", Constant.COMMON_STATUS_NORMAL);
        paramsNew.put("tenantId", tenantId);
        List<Map<String, Object>> list = stationMapper.getAllStationTreeUtilsByTenantId(paramsNew);
        List<TreeUtils> listTree = TreeUtils.getTreeListMap(list, "id", "parentId", "stationName", "disabledfn", "id");
        return listTree;
    }

    @Override
    public List<Station> queryStationByOrgIds(List<String> orgIds) {
        StationExample example = new StationExample();
        StationExample.Criteria criteria = example.createCriteria();
        criteria.andOrgIdIn(orgIds);
        example.setOrderByClause(" order_num ");
        List<Station> users = stationMapper.selectByExample(example);
        return users;
    }

    @Override
    public List<Station> getStationDataByOrgAndModule(Map<String, Object> params) {
        StationExample example = new StationExample();
        StationExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(params.get("moduleType"))) {
            criteria.andModuleTypeEqualTo(params.get("moduleType").toString());
        }
        if (StringUtils.isNotBlank(params.get("deptId"))) {
            criteria.andOrgIdEqualTo(params.get("deptId").toString());
        }
        example.setOrderByClause(" order_num ");
        List<Station> list = stationMapper.selectByExample(example);
        return list;
    }

    @Override
    public List<Map<String, Object>> getUserIdListByModuleAndStation(Map<String, Object> params) {
        if (StringUtils.isBlank(params.get("moduleType")) || StringUtils.isBlank(params.get("stationName"))) {
            return new ArrayList<Map<String, Object>>();
        }
        List<Map<String, Object>> userIdList = stationMapper.getUserIdListByModuleAndStation(params);
        return userIdList;
    }

    @Override
    public List<Station> getStationsByOrgId(String orgId, String moduleType) {
        StationExample example = new StationExample();
        StationExample.Criteria criteria = example.createCriteria();
        criteria.andOrgIdEqualTo(orgId);
        criteria.andStatusEqualTo("100101");
        if(StringUtils.isNotBlank(moduleType)){
            List<String> modList = new ArrayList<>(Arrays.asList(moduleType.split(",")));
            modList.add(Constant.SystemModule.sys.name());
            criteria.andModuleTypeIn(modList);
        }
        example.setOrderByClause(" order_num ");
        List<Station> list = stationMapper.selectByExample(example);
        return list;
    }

    @Override
    public boolean checkStationName(String orgId, String moduleType, String stationName) {
        Station station = this.getStationByOrgIdAndModuleTypeAndStationName(orgId, moduleType, stationName);
        if (ObjectUtils.isEmpty(station)) {
            return false;
        }
        return true;
    }

    @Override
    public Station getStationByOrgIdAndModuleTypeAndStationName(String orgId, String moduleType, String stationName) {
        StationExample example = new StationExample();
        StationExample.Criteria criteria = example.createCriteria();
        criteria.andOrgIdEqualTo(orgId);
        criteria.andModuleTypeEqualTo(moduleType);
        criteria.andStationNameEqualTo(stationName);
        List<Station> list = stationMapper.selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public JSONArray getStationDataByUserId(String userId) {
        UserStationExample example1 = new UserStationExample();
        UserStationExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andUserIdEqualTo(userId);
        List<UserStation> list = userStationMapper.selectByExample(example1);
        JSONArray jsonArrayByStation = new JSONArray();
        if (list.size() > 0) {
            Set<String> setStationOrgIds = new HashSet<String>();
            for (UserStation userStation : list) {
                Station station = stationMapper.selectByPrimaryKey(userStation.getStationId());
                setStationOrgIds.add(station.getOrgId());
            }
            for (String setStationOrgId : setStationOrgIds) {
                Org org = orgMapper.selectByPrimaryKey(setStationOrgId);
                Org parentOrg = orgMapper.selectByPrimaryKey(org.getParentId());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("orgId", setStationOrgId);
                jsonObject.put("orgName", parentOrg.getOrgName() + "---" + org.getOrgName());
                JSONArray jsonArray = new JSONArray();
                for (UserStation userStation : list) {
                    Station station = stationMapper.selectByPrimaryKey(userStation.getStationId());
                    if (setStationOrgId.equals(station.getOrgId())) {
                        JSONObject json = new JSONObject();
                        json.put("id", userStation.getId());
                        json.put("stationId", station.getId());
                        json.put("stationName", station.getStationName());
                        json.put("moduleType", station.getModuleType());
                        jsonArray.add(json);
                    }
                }
                jsonObject.put("stationData", jsonArray);
                jsonArrayByStation.add(jsonObject);
            }

        }
        return jsonArrayByStation;
    }


    @Override
    public List<Station> queryStationByDeptId(String deptId) {
        StationExample example = new StationExample();
        StationExample.Criteria criteria = example.createCriteria();
        criteria.andOrgIdEqualTo(deptId);
        example.setOrderByClause(" order_num ");
        List<Station> users = stationMapper.selectByExample(example);
        return users;
    }
}
